package com.fjbdxk.beidou.net;

import com.fazecast.jSerialComm.SerialPort;
import com.fjbdxk.beidou.core.AbstractBeiDouMessage;
import com.fjbdxk.beidou.core.AbstractBeiDouNet;
import com.fjbdxk.beidou.msg.BDFKIMessage;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Socket通信
 *
 * @author huanggy
 * @version 1.0.0
 * @date 2024/05/13
 **/
@RequiredArgsConstructor
public class SocketBeiDouNet extends AbstractBeiDouNet {

    private Socket socket;
    @NonNull
    private String ip = "192.168.1.39";
    @NonNull
    private int port = 12345;

    /**
     * 打开与服务器的 Socket 连接
     * @return
     */
    @Override
    public boolean open() {
        if (socket == null) {
            try {
                socket = new Socket(ip, port);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * 关闭与服务器的 Socket 连接
     * @return
     */
    @Override
    public boolean close() {
        if (socket == null) {
            return true;
        } else {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return socket.isClosed();
        }
    }

    /**
     * 发送消息并接收反馈
     * @param message
     * @return
     */
    @Override
    public String doSend(AbstractBeiDouMessage message) {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(message.getMshByte());
            // 休眠一会
            Thread.sleep(100);

            byte[] buffer = new byte[1024];
            int len = inputStream.read(buffer);
            if (len > 0) {
                String receivedMessage = new String(buffer, 0, len);
                System.out.println(receivedMessage);
                return receivedMessage;
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
